/**
 * FileName: RestExceprionHandler
 * Author: zlz
 * CreatedDate: 2025/3/3 11:09:40
 * Description: 统一异常处理器
 * Version: 1.0.0
 */
package com.zlz.parent.basic.springboot.starter.config;

import com.zlz.base.entity.response.ResultSet;
import com.zlz.base.exception.BizException;
import com.zlz.parent.basic.springboot.starter.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * @author zlz
 * @date 2025/3/3 11:09:40
 * @description 统一异常处理器
 */
@Slf4j
@Component
public class RestExceptionFilter implements WebFilter, Ordered {

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE + 99;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        return chain.filter(exchange).onErrorResume(e -> {
            ServerHttpRequest request = exchange.getRequest();
            log.error("请求状态异常：{}", request.getURI().getPath());
            log.error(e.getMessage(), e);
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.OK);
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return ResponseUtils.writeSuccess(response, e instanceof BizException ?
                    ResultSet.error(((BizException) e).getCode(), e.getMessage())
                    : ResultSet.error());
        });
    }
}
